<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

/**
 * Description of product
 *
 * @author b4by
 */
class product extends MY_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('model_product');
		$this->load->model('model_product_catalogue');
		$this->load->model('model_product_info');
		$this->load->model('model_product_location');
		$this->load->model('model_product_discount');
		$this->load->model('model_product_image');
		$this->data['errors'] = array();
	}

	public function index() {
		$this->data['temp'] = 'admin/product/index';
		$this->load->view('admin/main', $this->data);
	}

    public function read() {
        $pagination = pagination_init($this->model_product->get_total(), request('p'));

        $products = $this->model_product->get_list($this->siteConfig->lang, array(
            'limit' => array($pagination->from, $pagination->limit)
        ));
        

        foreach($products as &$product){
            $product->thumb = image_url($product->thumb);
            $product->price = currency_format($product->price);//number_format($product->price,0,$this->uconfig->dec_point,$this->uconfig->thousands_sep);
            $product->sale_price = currency_format($product->sale_price);//number_format($product->sale_price,0,$this->uconfig->dec_point,$this->uconfig->thousands_sep);
            $product->edit_link = url_create('admin','product','update',$product->id);
        }
        echo json_encode(array(
            'state' => 'success',
            'data' => $products,
            'pagination' => $pagination,
        ));
    }

	public function create() {
		$error = array();
		$this->data['product'] = array();
//		pr($_POST);die;
		if ($this->input->post('submit')) {
			$this->data['product'] = request_filter(array('price','sale_price','start','end','info','locations','catalogues','amount','voucher'));
			$this->_valid_form();
			if ($this->form_is_valid()) {
                if(isset($_FILES['image'])){
                    $image = $this->upload_image('image');
                    if($image===false){
                        $error['image'] = lang('upload_error');
                        goto error;
                    }else{
                        $data = request_filter(array('price', 'sale_price', 'start', 'end','amount','voucher'));
                        $data['image'] = $image->path;
                        $data['thumb'] = $image->thumb;
                    }
                }
				$data['start'] = datetotime($data['start']);
				$data['end'] = datetotime($data['end']);
				$product_id = $this->model_product->create($data);
				$info = request('info');

                // Info
				foreach ($this->languages as $lang) {
					$info[$lang->id]['product_id'] = $product_id;
					$info[$lang->id]['lang_id'] = $lang->id;
				}
				foreach ($info as $row) {
					$this->model_product_info->create($row);
				}

                // Catalogue
				$catalogues = request('catalogues');
				foreach ($catalogues as $catalogue)
					$this->model_product_catalogue->create(array(
						'product_id' => $product_id,
						'cat_id' => $catalogue,
					));

                // Location
				$locations = request('locations');
				foreach ($locations as $location)
					$this->model_product_location->create(array(
						'product_id' => $product_id,
						'location_id' => $location,
					));

                // Images
				foreach ($_FILES as $key => $value) {
					if (preg_match('/images_/', $key) == 0)
						continue;
					if ($_FILES[$key]['size'] == 0)
						continue;
					$image = $this->upload_image($key);
					if ($image !== false) {
						$this->model_product_image->create(array(
							'product_id' => $product_id,
							'path' => $image->path,
							'thumb' => $image->thumb,
						));
					}
				}
				redirect(url_create('admin', 'product', 'index'));
			}
		}	
		error:
		$this->_init();
		$this->data['temp'] = 'admin/product/create';
		$this->load->view('admin/main', $this->data);
	}

	function update($id) {
		$this->data['errors'] = array();
        $product = $this->model_product->get_info($id);
        if($product===false)
        {
            show_error(lang('product_not_found'));
        }
		
        $product->start = date($this->languages[$this->user_lang->id]->date_format,$product->start);
        $product->end = date($this->languages[$this->user_lang->id]->date_format,$product->end);
        $product->thumb = image_url($product->thumb);
        if($product->images!==false)
            foreach($product->images as &$image)
            {
                $image->path = image_url($image->path);
                $image->thumb = image_url($image->thumb);
            }
        $this->data['product'] = $product;
//		pr($product);die;
        if($this->input->post('submit'))
        {
            $data = request_filter(array('price','sale_price','start','end','info','locations','catalogues','amount','voucher'));
//			pr($data);die;
            $product_id = request('id');
			$this->_valid_form($product_id);
            if ($this->form_is_valid()) {
                $data = request_filter(array('price', 'sale_price', 'start', 'end','amount','voucher'));

                if($_FILES['image']['size']!=0){
                    $image = $this->upload_image('image');
                    $data['image'] = $image->path;
                    $data['thumb'] = $image->thumb;
                    unlink( BASEPATH . $product->image);
                    unlink(BASEPATH . $product->thumb);
                }

				$data['start'] = datetotime($data['start']);
				$data['end'] = datetotime($data['end']);
				if($data['voucher']!=1) $data['voucher']=0;
				
                $this->model_product->update($product_id,$data);


                $info = request('info');

                // Info
                foreach ($this->languages as $lang) {
                    $info[$lang->id]['product_id'] = $product_id;
                    $info[$lang->id]['lang_id'] = $lang->id;
                }
                foreach ($info as $row) {
                    $this->model_product_info->update_rule(array(
                        'product_id'   => $product_id,
                        'lang_id'   => $row['lang_id'],
                    ),$row);
                }

                // Catalogue
                $catalogues = request('catalogues');
                $this->model_product_catalogue->del_rule(array(
                    'product_id'    => $product_id,
                ));
                foreach ($catalogues as $catalogue)
                    $this->model_product_catalogue->create(array(
                        'product_id' => $product_id,
                        'cat_id' => $catalogue,
                    ));

                // Location
                $locations = request('locations');
                $this->model_product_location->del_rule(array('product_id'  => $product_id));
                foreach ($locations as $location)
                    $this->model_product_location->create(array(
                        'product_id' => $product_id,
                        'location_id' => $location,
                    ));

                // Images
                foreach ($_FILES as $key => $value) {
                    if (preg_match('/images_/', $key) == 0)
                        continue;
                    if ($_FILES[$key]['size'] == 0)
                        continue;
                    $image = $this->upload_image($key);
                    if ($image !== false) {
                        $this->model_product_image->create(array(
                            'product_id' => $product_id,
                            'path' => $image->path,
                            'thumb' => $image->thumb,
                        ));
                    }
                }

                redirect(url_create('admin', 'product', 'index'));
            }
        }
		
		$this->_init();

        $this->data['temp'] = 'admin/product/update';
		$this->load->view('admin/main',$this->data);
	}

	function delete() {
		$id = request('id');
		$images = $this->model_product_image->get_list(array('product_id' => $id));
		foreach ($images as $image) {
			if (file_exists($image->path))
				unlink($image->path);
			if (file_exists($image->thumb))
				unlink($image->thumb);
		}
		$info = $this->model_product->get_info($id);

		if (file_exists($info->image))
			unlink($info->image);
		if (file_exists($info->thumb))
			unlink($info->thumb);
		$this->model_product_image->del_rule(array('product_id' => $id));
		$this->model_product_info->del_rule(array('product_id' => $id));
		$this->model_product_location->del_rule(array('product_id' => $id));
		$this->model_product_image->del_rule(array('product_id' => $id));

		$this->model_product->del($id);
		echo json_encode(array(
			'state' => 'success',
			'id' => $id,
		));
	}

    public function delete_image(){
        $id = request('id');
        $image = $this->model_product_image->get_info($id);
        if($image===false)
        {
            echo json_encode(array(
                'state' => 'error',
                'title' => lang('error'),
                'message'   => lang('image_not_found')
            ));
        }
        else{
            $this->_delete_image($image->path);
            $this->_delete_image($image->thumb);
            $this->model_product_image->del($id);
            echo json_encode(array(
                'state' => 'success',
                'id'    => $id
            ));
        }
    }
    public function _valid_form($id=false)
    {
        $this->load->helper('form');
        $this->load->library('form_validation');
        if($id!==false)
            $this->form_validation->set_rules('id','lang:product','callback__check_product_id');
		$this->form_validation->set_rules('amount','lang:amount','required|is_natural_no_zero');
//		$this->form_validation->set_rules('voucher','lang:voucher','required');
        $this->form_validation->set_rules('price', 'lang:product_price', 'callback__check_price');
        $this->form_validation->set_rules('sale_price', 'lang:product_sale_price', 'callback__check_price');
        $this->form_validation->set_rules('start', 'lang:product_start', 'callback__check_date');
        $this->form_validation->set_rules('end', 'lang:product_end', 'callback__check_date');
        $this->form_validation->set_rules('info', 'lang:product_info', 'callback__check_info');
        $this->form_validation->set_rules('catalogues', 'lang:product_catalogue', 'callback__check_catalogue');
        $this->form_validation->set_rules('locations', 'lang:product_location', 'callback__check_location');
        return $this->form_is_valid();
    }

	public function _init()
	{
		$this->load->model('model_catalogue');
		$this->load->model('model_location');
		$catalogues = $this->model_catalogue->get_list_hash($this->siteConfig->lang, array(
			'order' => array('index', 'asc')
				));
		$locations = $this->model_location->get_list_hash(array(
			'order' => array('index', 'asc')
				));

		array_to_object($catalogues);
		object_prefix_create($catalogues, '', '&nbsp;&nbsp;&nbsp;&nbsp;');
		$this->data['catalogues'] = array();
		object_to_array($this->data['catalogues'], $catalogues);

		array_to_object($locations);
		object_prefix_create($locations, '', '&nbsp;&nbsp;&nbsp;&nbsp;');
		$this->data['locations'] = array();
		object_to_array($this->data['locations'], $locations);
	}

    public function _check_product_id($id)
    {
        if($this->model_product->get_total(array('id' => $id))==0)
        {
            $this->form_validation->set_message(__FUNCTION__,lang('product_not_found'));
            return false;
        }
        return true;
    }


	public function _check_date($str) {

		$format = $this->siteConfig->date_format;
		switch ($format) {
			case 'yyyy/mm/dd':
				if (preg_match("/^(19\d\d|2\d\d\d)[\/|-](0?[1-9]|1[012])[\/|-](0?[1-9]|[12][0-9]|3[01])$/", $str, $match) && checkdate($match[2], $match[3], $match[1])) {
					return TRUE;
				}
				break;
			case 'mm/dd/yyyy':
				if (preg_match("/^(0?[1-9]|1[012])[\/|-](0?[1-9]|[12][0-9]|3[01])[\/|-](19\d\d|2\d\d\d)$/", $str, $match) && checkdate($match[1], $match[2], $match[3])) {
					return TRUE;
				}
				break;
			default: // 'dd/mm/yyyy'
				if (preg_match("/^(0?[1-9]|[12][0-9]|3[01])[\/|-](0?[1-9]|1[012])[\/|-](19\d\d|2\d\d\d)$/", $str, $match) && checkdate($match[2], $match[1], $match[3])) {
					return TRUE;
				}
				break;
		}
        $this->form_validation->set_message(__FUNCTION__,lang('invalid_date_format'));
		return FALSE;
	}

	public function _check_location($value) {
        if(!is_array($value))
        {
            $this->form_validation->set_message(__FUNCTION__,lang('location_required'));
            return false;
        }
		$this->load->model('model_location');
		foreach ($value as $location_id) {
			if ($this->model_location->get_total(array('id' => $location_id)) == 0) {
				$this->form_validation->set_message(__FUNCTION__, lang('product_invalid_location'));
				return false;
			}
		}
		return true;
	}

	public function _check_catalogue($value) {
        if(!is_array($value))
        {
            $this->form_validation->set_message(__FUNCTION__,lang('catalogue_required'));
            return false;
        }
		$this->load->model('model_catalogue');
		foreach ($value as $catalogue_id) {
			if ($this->model_catalogue->get_total(array('id' => $catalogue_id)) == 0) {
				$this->form_validation->set_message(__FUNCTION__, lang('product_invalid_catalogue'));
				return false;
			}
		}
		return true;
	}

	public function _check_price($value) {
		if (is_numeric($value))
			if ($value >= 0)
				return true;
		$this->form_validation->set_message(__FUNCTION__, lang('price_not_valid'));
		return false;
	}

	public function _check_info($value) {
        if(!is_array($value))
        {
            $this->form_validation->set_message(__FUNCTION__,lang('invalid_data'));
            return false;
        }
		foreach ($this->languages as $lang) {
			if (!isset($value[$lang->id])) {
				$this->form_validation->set_message(__FUNCTION__, lang('product_info_invalid'));
				return false;
			} else if (!isset($value[$lang->id]['name']) || strlen($value[$lang->id]['name']) == 0) {
				$this->form_validation->set_message(__FUNCTION__, lang('product_name_required'));
				return false;
			}
		}
		return true;
	}

}

?>
